<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <title>Coupon Details</title>
    <link rel="shortcut icon" href="./imgs/favicon.png" type="image/x-icon">
    <link rel="stylesheet" href="./css/detail.css">
    <link rel="stylesheet" href="./plugins/Swiper/swiper-bundle.min.css">
    <!-- <script src="./js/vue@2.js"></script> -->
    <script src="./js/vue@2.js"></script>
</head>
<style>
    [v-cloak] {
        display: none;
    }
</style>
<body>
    <div id="app">
        <div class="header">
            <div class="header-content">
                <div class="header-content-normal">
                    <div class="header-content-search" @click="handleToSearch"></div>
                    <span class="header-content-normal_title" v-cloak>{{detail.title}}</span>
                    <div class="header-content-menu" @click="showMenu = true"></div>
                </div>
                <div class="nav" :class="{open: showMenu}">
                    <a class="nav-item" href="index.html"><span>Home</span></a>
                    <a class="nav-item" :href="`type.html?type=${encodeURIComponent(item)}`" v-for="item in categories">
                        <span>{{item}}</span>
                    </a>
                </div>
                <div class="nav-mask" v-show="showMenu" @click="showMenu = false"></div>
            </div>

            <div class="search">
                <input class="search_input" type="text" v-model="keywords" placeholder="Search ...">
                <div class="search-btn" @click="handleToSearch">
                <img class="search-btn_img" src="./imgs/icon-search.png" alt="search_icon" width="20">
                </div>
            </div>
        </div>

        <main class="main" v-cloak>
            <div class="swiper">
                <div class="swiper-wrapper">
                    <div class="swiper-slide" v-for="img in images">
                        <div class="award">
                            <img class="award_img" :src="img" :alt="detail.title">
                        </div>
                    </div>
                </div>
                <div class="swiper-pagination"></div>
            </div>


            <div class="block">
                <!-- <div class="point">
                    <span class="point_span">{{detail.consumePoints}}</span>
                    <span class="point_icon"></span>
                </div> -->
                <div class="title">
                    <h4 class="point_title" v-cloak>{{detail.title}}</h4>
                </div>
            </div>
            <div class="block">
                <div class="content" v-for="item in article">
                    <h4 v-cloak>{{item.title}}</h4>
                    <p v-html="replaceText(item.content)"></p>
                </div>
            </div>
            <div v-cloak class="btn" :class="{use: detail.isUsed == 1}" @click="toPage">
                Go Shopping
            </div>
        </main>
        <div class="footer">
            <div class="footer-nav">
                <a href="./cookies-policy.html">Cookies Policy</a>
                <a href="./privacy-policy.html">Privacy Policy</a>
                <a href="javascript:;">We updated our Terms of Service on Aug 4, 2023.</a>
                <a href="javascript:;">©2023 Clutch.co. All rights reserved.</a>
            </div>
        </div>

        <div class="toast" :class="{show: showToast}">Not enough fire to consume</div>
        <div class="mask" :class="{loading: load}">
            <img src="./imgs/loading.svg" alt="loading" width="50">
        </div>
    </div>
</body>


<script src="./plugins/Swiper/swiper-bundle.min.js"></script>
<script>
    function debounce(fn, delay) {
        let timer = null
        return function () {
            let that = this
            let args = arguments
            if (timer) {
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                fn.apply(that, args)
                clearTimeout(timer)
                timer = null
            }, delay)
        }
    }
</script>
<script>
    var vm = new Vue({
        el: '#app',
        data() {
            return {
                detail: {},
                article: [],
                toast: '',
                showToast: false,
                load: false,
                swiper: null,
                categories: {
                    1: 'Electronics',
                    2: 'Auto Insurance',
                    3: 'Apparel&Shoes',
                    4: 'Beauty Makeup',
                    5: 'Toys Games'
                },
                showMenu: false,
                keywords: ''
            }
        },
        computed: {
            getBtnText() {
                return this.detail.isUsed == 0 ? 'Redeem' : 'Use'
            },
            images() {
                let imgs = []
                if (this.detail.image) {
                    imgs =  this.detail.image.split(',') || []
                } else {
                    imgs = this.detail.icon.split(',') || []
                }
                return imgs
            }
        },
        created() {
            this.detail = this.getQueryVariable('data') && JSON.parse(decodeURIComponent(this.getQueryVariable('data')))
            this.createArticleData()
        },
        mounted() {
            this.$nextTick(() => {
                this.renderSwiperModule()   
            })
        },
        methods: {
            handleToSearch() {
                window.location.href = `search.html?keywords=${this.keywords}`
            },
            toPage() {
                window.location.href = this.detail.couponUrl
            },
            back() {
                window.history.back()
            },
            renderSwiperModule() {
                this.swiper = new Swiper('.swiper', {
                    loop: true, // 无限滚动
                    autoplay: true,//可选选项，自动滑动
                    pagination: {
                        el: '.swiper-pagination',
                        type: 'fraction'
                    }
                })
            },
            handleCouponMethods: debounce(function () {
                // 未兑换
                if (this.detail.isUsed == 0) {
                    this.fetchExchangeCoupon()
                    return
                }

                // 已兑换
                if (this.detail.isUsed == 1) {
                    android.useCouponUrl(this.detail.couponUrl)
                    return
                }
            }, 500),
            fetchExchangeCoupon() {
                this.load = true
                fetch('https://apitest.92onegame.com/bibleApi/tUserPointsDetail/addPointsDetailNew', {
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8'
                    },
                    method: 'post',
                    body: JSON.stringify({
                        deviceInfo: this.detail.device,
                        points: this.detail.consumePoints,
                        pointsType: 24,
                        couponId: this.detail.id
                    })
                })
                    .then(res => res.json())
                    .then(res => {
                        this.load = false
                        if (res.code === 0) {
                            android.showRedeemSuccess(this.detail.couponUrl, this.detail.title)
                            android.logRedeemSuccess(this.detail.id, this.detail.title, this.detail.consumePoints)
                            this.detail.isUsed = 1
                            return
                        }

                        if (res.code === 407) {
                            android.showRedeemFailed()
                        } else {
                            this.handleMessage(res.msg, 1800)
                        }
                        android.logRedeemFailed(res.code, this.detail.id, this.detail.title, this.detail.consumePoints)
                    })
                    .catch(err => {
                        this.load = false
                    })
            },
            handleMessage(msg, delay) {
                this.toast = msg
                this.showToast = true
                setTimeout(() => {
                    this.showToast = false
                }, delay)
            },
            replaceText(text) {
                const regex = new RegExp(/<|>/, 'g')
                const textMap = {
                    '<': '<strong style="color:#6fb95a">',
                    '>': '</\strong>'
                }
                const string = text.replace(regex, (item) => {
                    return textMap[item]
                })

                return string
            },
            handleToHome() {
                window.history.back()
            },
            createArticleData() {
                this.article = [
                    { title: 'Brand Introduction:', content: this.detail.descInfo },
                    { title: 'Redemption Method:', content: 'Click Go Shopping to use it' },
                    { title: 'Expiration date of the Coupon:', content: 'Valid for 24 hours from the date of redemption.' },
                    { title: 'Return and Exchange Policy', content: 'Once exchanged, no returns or exchanges are supported.' }
                ]
            },
            getQueryVariable(variable) {
                var query = window.location.search.substring(1);
                var vars = query.split("&");
                for (var i = 0; i < vars.length; i++) {
                    var pair = vars[i].split("=");
                    if (pair[0] == variable) { return pair[1]; }
                }
                return (false);
            }
        }
    })
</script>
<style>
.swiper-pagination, .swiper-pagination span {
    color: #ffffff;
}
</style>
</html>